module ActiveRecord
  module Associations
    module ClassMethods
      class JoinDependency # :nodoc:
        def remove_duplicate_results!(base, records, associations)
          case associations
          when Symbol, String
            reflection = base.reflections[associations]
            if reflection && [:has_many, :has_and_belongs_to_many].include?(reflection.macro)
              records.each { |record| record.send(reflection.name).target.uniq! }
            end
          when Array
            associations.each do |association|
              remove_duplicate_results!(base, records, association)
                end
          when Hash
            associations.keys.each do |name|
              # error at TasksController#week_tasks_for_member
              # reflection = base.reflections[name]
              reflection = base.reflections[name] or next
              
              is_collection = [:has_many, :has_and_belongs_to_many].include?(reflection.macro)
              
              parent_records = records.map do |record|
                descendant = record.send(reflection.name)
                next unless descendant
                descendant.target.uniq! if is_collection
                descendant
              end.flatten.compact
              
              remove_duplicate_results!(reflection.class_name.constantize, parent_records, associations[name]) unless parent_records.empty?
            end
          end
        end
      end
    end
  end
end
